package com.chen.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

// 实现精准通信 A 执行完调用B，B执行完调用C，C执行完调用A
public class PC_lockPlus {
    public static void main(String[] args) {

        Data3 data3 = new Data3();

        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                data3.printA();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                data3.printB();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                data3.printC();
            }
        }, "C").start();

    }
}

// 资源类 lock
class Data3 {

    private ReentrantLock lock = new ReentrantLock();
    // 同步监视器，1对应A，2对应B，3对应C
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    // 通信标志位
    private int num = 1;

    public void printA() {
        lock.lock();
        try {
            // 判断是否等待
            while (num != 1) {
                condition1.await();
            }
            // 执行
            System.out.println(Thread.currentThread().getName());
            // 唤醒B
            num = 2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            // 判断是否等待
            while (num != 2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName());
            // 唤醒C
            num = 3;
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            // 判断是否等待
            while (num != 3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName());
            // 唤醒A
            num = 1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}


